<template>
  <view :class="classNameList">
    <template v-if="isPromotion">
      <view class="_product_price">
        <view class="_center">
          <view class="_dt">
            <view class="_new_name">{{ coupon ? '券后' : '到手' }}：</view>
            <view class="_new_price" :data-value="payPrice.suffix">{{ payPrice.prefix }}</view>
            <template v-if="coupon">
              <view class="_new_pro_name">大促底价</view>
              <view class="_new_pro_price" :data-value="promotionPrice.suffix">{{ promotionPrice.prefix }}</view>
            </template>
          </view>
          <view class="_dd">
            <view class="_old_price" :data-value="originalPrice.suffix">{{ originalPrice.prefix }}</view>
            <view class="_tag">大促直降{{promotionDiscountAmount}}元</view>
            <view v-if="hotSales" class="_sales">{{sales}}</view>
          </view>
        </view>
      </view>
      <view class="_promotion">
        <view class="_dt">{{priceModule.salesTitle}}</view>
        <view class="_dd">{{priceModule.salesTitleSuffix || '大促'}}</view>
      </view>
    </template>
    <template v-else-if="showSubsidy">
      <view class="banner-bg">
        <x-image src="/assets/images/open-banner-bg.png" mode="widthFix" />
      </view>
      <view class="subsidy-price-bar">
        <view class="left">
          <view class="final-price">
            <view class="prefix">最低到手 ¥</view>
            <view class="amount">{{ subsidyPrice.value }}</view>
          </view>
          <view class="discount">
            <view class="amount">已补贴{{subsidyAmount}}元</view>
            <view class="original">即将恢复¥{{pagePrice}}</view>
          </view>
        </view>
        <view class="right">
          <view>超值补贴</view>
          <view class="ul countdown">
            <view class="li">{{countdownData.minute}}</view>
            <view class="delimiter">:</view>
            <view class="li">{{countdownData.second}}</view>
            <view class="delimiter">:</view>
            <view class="li">
              <template v-if="countdownData.remain === 0">00</template>
              <view v-else class="millisecond">
                <x-image src="/assets/images/countdown-hui.gif" mode="widthFix" />
              </view>
            </view>
            <x-countdown
              v-if="showCountdown"
              :time="300000"
              auto
              @change="handleCountdownChange"
            />
          </view>
        </view>
      </view>
      <view v-if="hotSales && !isTemplate3" class="_sales">{{sales}}</view>
    </template>
    <template v-else-if="isTemplate3">
      <view v-if="priceModule" class="template3-price-bar">
        <view class="left">
          <template v-if="crossedPrice">
            <view class="final-price">
              <view v-if="crossedPrice" class="prefix">活动价 ¥</view>
              <view class="amount">
                <x-count-to :start-val='pageHighPrice' :end-val='payPrice.value' />
              </view>
              <view v-if="reductionAmount" class="discount">直降{{ reductionAmount }}元</view>
            </view>
            <view v-if="reductionAmount" class="original">即将恢复¥{{pageHighPrice}}</view>
          </template>
          <view v-else class="amount">
            <view class="final-price">
              <view class="prefix">¥</view>
              <view class="amount">
                {{ payPrice.value }}
              </view>
            </view>
          </view>
        </view>
        <view class="right">
          <view class="countdown-title">距结束还剩</view>
          <view class="ul countdown">
            <view class="li">{{countdownData.hour}}</view>
            <view class="delimiter">:</view>
            <view class="li">{{countdownData.minute}}</view>
            <view class="delimiter">:</view>
            <view class="li">{{countdownData.second}}</view>
            <x-countdown
              v-if="showCountdown"
              :time="time"
              auto
              @change="handleCountdownChange"
            />
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <view v-if="priceModule" class="_default_price">
        <template v-if="coupon">
          <view class="_price" :data-value="originalPrice.suffix">
            {{ originalPrice.prefix }}
          </view>
          <view class="_coupon">
            <view class="_coupon_name">券后</view>
            <view class="_coupon_price" :data-value="payPrice.suffix">
              {{ payPrice.prefix }}
            </view>
          </view>
        </template>
        <view v-else class="_price" :data-value="payPrice.suffix">
          {{ payPrice.prefix }}
        </view>
      </view>
      <view v-if="hotSales" class="_sales">{{sales}}</view>
    </template>
  </view>
</template>

<script>
import { mapState } from 'vuex';
import XImage from '@/components/x-image';
import XCountdown from '@/components/x-countdown';
import XCountTo from '@/components/x-count-to';

export default {
  name: 'PPrice',
  components: {
    XImage,
    XCountdown,
    XCountTo
  },
  props: {
    query: {
      type: Object,
      default: () => {}
    },
    isTemplate3: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showCountdown: true,
      countdownData: {}
    };
  },
  computed: {
    ...mapState({
      // 页面销量
      pageSales: state => state['product'].pageDetail.pageSales,
      // 销量模块
      hotSales: state => state['product'].pageModule.hotSales,
      // 划线价
      crossedPrice: state => state['product'].pageModule.crossedPrice,
      // 页面价格
      pagePrice: state => state['product'].pageDetail.pagePrice,
      // 页面单买价
      pageHighPrice: state => state['product'].pageDetail.pageHighPrice,
      // 价格模块
      priceModule: state => state['product'].pageModule?.price,
      // 超值补贴模块
      superSubsidyModule: state => state['product'].pageModule?.superSubsidy,
      // 商品可用优惠券
      couponList: state => state['product'].couponList,
      // 用户当前选择的优惠券信息
      userSelectCoupon: state => state['product'].userSelectCoupon,
      // 规格模式：1-统一规格；2-多规格；3-套餐模式
      skuMode: state => state['product'].productDetail?.skuMode,
      // 用户挽留弹框配置的优惠数组
      exitPopupList: state => state['pages'].exitPopupList,
      // 用户挽留弹框配置的优惠展示过的下标
      exitPopupIndex: state => state['pages'].exitPopupIndex,
      // 页面信息
      pageInfo: state => state['product'].pageDetail
    }),
    classNameList() {
      const arr = ['p-price'];
      if (this.isPromotion) {
        arr.push('is-promotion');
      } else if (this.showSubsidy) {
        arr.push('is-subsidy');
      } else if (this.isTemplate3) {
        arr.push('is-template-3');
      } else {
        arr.push('is-default');
      }
      if (!this.priceModule && !this.hotSales && !this.isSuperSubsidy) {
        arr.push('is-empty');
      }
      return arr.join(' ');
    },
    sales() {
      if (this.hotSales) {
        const val = this.$tools.formatNumber(this.pageSales + this.hotSales.value);
        return `已售${this.$tools.numberFormat(val)}${val >= 10000 ? '+' : ''}件`;
      } else {
        return '';
      }
    },
    // 大促展示样式
    isPromotion() {
      return !!(this.priceModule && this.priceModule?.value === 2);
    },
    // 超值补贴样式
    isSuperSubsidy() {
      return this.superSubsidyModule;
    },
    // 大促金额
    promotionDiscountAmount() {
      return this.isPromotion ? this.priceModule?.discountAmount : 0;
    },
    // 超值补贴金额
    subsidyAmount() {
      return this.isSuperSubsidy ? this.isSuperSubsidy?.value : 0;
    },
    // 商品原价
    originalPrice() {
      const arr = this.$tools.formatZero(this.pageHighPrice).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: this.pageHighPrice,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 大促底价
    promotionPrice() {
      // 当前商品售价为大促后的价格，若有挽回逻辑，在大促的金额上减去挽回金额
      // 原价 - 大促 - (优惠券 || 挽回金额)，优先优惠券
      let price = this.$tools.formatNumber(this.pagePrice - this.promotionDiscountAmount);
      // 有优惠券的时候，这里不减挽回金额
      if (!this.coupon) {
        if (this.currentExitPopup) {
          price = this.$tools.formatNumber(price - this.currentExitPopup.discountAmount);
        } else if (this.query.discountAmount) {
          price = this.$tools.formatNumber(price - this.query.discountAmount);
        }
      }
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[0] === '0' && arr[1] === '00' ? '01' : arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 当前挽留弹窗数据
    currentExitPopup() {
      return this.query.source === 'stay' && this.exitPopupList?.length ? this.exitPopupList[this.exitPopupIndex - 1] : null;
    },
    // 优惠券
    coupon() {
      if (this.userSelectCoupon && this.couponList && this.couponList.length) {
        // 原价 - 大促 - 优惠券
        const couponList = this.couponList;
        return couponList.sort((a, b) => {
          return b.couponAmount - a.couponAmount;
        })[0];
      } else {
        return null;
      }
    },
    // 最终支付价
    payPrice() {
      // 计算逻辑为先大促再用券（满减券需在大促后计算是否满足用券条件）
      let price = this.promotionPrice.value;
      if (this.coupon) {
        // 原价 - 大促 - 优惠券
        const coupon = this.coupon;
        if (coupon.couponType === 2) {
          // 直减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        } else if (price >= coupon.transactionAmount) {
          // 满减券
          price = this.$tools.formatNumber(price - coupon.couponAmount);
        }
      }
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[1]}`);
      }
      if ([2, 3].includes(this.skuMode)) {
        suffix.push('起');
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },
    // 补贴价
    subsidyPrice() {
      let price = this.$tools.formatNumber(this.pagePrice - this.subsidyAmount);
      if (price <= 0) {
        price = 0.01;
      }
      const arr = this.$tools.formatZero(price).split('.');
      const suffix = [];
      if (arr && arr.length === 2) {
        suffix.push(`.${arr[0] === '0' && arr[1] === '00' ? '01' : arr[1]}`);
      }
      return {
        value: price,
        prefix: arr[0],
        suffix: suffix.join('')
      };
    },

    showSubsidy() {
      return this.isSuperSubsidy && !this.currentExitPopup && !this.query.discountAmount && !this.isFromCouponCards;
    },

    isFromCouponCards() {
      return ['1008'].includes(this.query.source);
    },

    reductionAmount() {
      return this.$tools.formatNumber(this.pageHighPrice - this.pagePrice);
    },

    time() {
      return this.pageInfo?.remainingSeconds ? this.pageInfo?.remainingSeconds * 1000 : 0;
    }
  },
  watch: {},
  created() {

  },
  methods: {
    handleCountdownChange(res) {
      this.countdownData = res;
      if (res.remain === 0) {
        this.showCountdown = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
  .p-price{
    background: #fff;
    // 默认
    &.is-default{
      padding: 20px 20px 20px; display: flex; align-items: center;
      ._default_price{
        display: flex;
        ._price{
          font-size: 54px; display: flex; align-items: flex-end; font-weight: bold; margin-right: 13px; color: #DE3A2E; line-height: 1;
          &:before{ content: '￥'; font-size: 26px; padding-bottom: 8px;}
          &:after{ content: attr(data-value); font-size: 28px; padding-bottom: 8px; font-weight: normal;}
        }
        ._coupon{
          display: flex; align-items: center; line-height: 1; font-weight: bold; color: #fff; background: linear-gradient(270deg, #FF3A0F 0%, #FF7C32 101.23%); border-radius: 50px; padding: 10px 20px;
          ._coupon_name{ font-size: 28px;}
          ._coupon_price{
            display: flex; align-items: flex-end; font-size: 50px;
            &:before{ content: '￥'; font-size: 26px; padding-bottom: 8px;}
            &:after{ content: attr(data-value); font-size: 28px; padding-bottom: 6px; font-weight: normal;}
          }
        }
      }
      ._sales{ color: #646464; font-size: 24px; flex: 1; text-align: right;}
    }

    // 大促
    &.is-promotion{
      background: #DE3A2E; color: #fff; border-bottom: 10px solid #fff; display: flex;
      ._product_price{
        flex: 1; padding: 22px 24px; display: flex; align-items: center;
        ._center{ flex: 1;}
        ._dt{
          display: flex; align-items: center; line-height: 1;
          ._new_name{ font-weight: bold; font-size: 28px;}
          ._new_price{
            font-size: 46px; display: flex; align-items: flex-end; font-weight: bold; margin-left: -15px; margin-right: 13px;
            &:before{ content: '￥'; font-size: 26px; padding-bottom: 5px;}
            &:after{ content: attr(data-value); font-size: 28px; padding-bottom: 5px; font-weight: normal;}
          }
          ._new_pro_name{ font-size: 24px;}
          ._new_pro_price{
            display: flex; align-items: flex-end;
            &:before{ content: '￥'; font-size: 20px; padding-bottom: 5px;}
            &:after{ content: attr(data-value); font-size: 20px; padding-bottom: 3px; font-weight: normal;}
          }
        }
        ._dd{
          display: flex; align-items: center; font-size: 24px; line-height: 1; padding-top: 14px;
          ._old_price{
            margin-right: 10px; margin-left: -14px; display: flex; align-items: flex-end; text-decoration:line-through;
            &:before{ content: '￥'; font-size: 20px;}
            &:after{ content: attr(data-value); font-size: 20px; font-weight: normal; padding-top: 3px;}
          }
          ._tag{ color: #AF231C; line-height: 1; background-color: #FFDA84; border-radius: 20px; padding: 4px 10px; font-size: 26px; font-weight: bold;}
          ._sales{ flex: 1; font-size: 24px; text-align: right;}
        }
      }
      ._promotion{
        display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; line-height: 1; min-width: 160px; color: #AF231C; background: linear-gradient(270deg, #FFC774 0.08%, #FFE580 101.58%); font-weight: bold; padding: 10px; position: relative;
        ._dt{ font-size: 50px; padding-bottom: 8px;}
        ._dd{ font-size: 44px;}
        &:before{ position: absolute; content: ''; left: -18px; border-radius: 3px; top: 50%; transform: translate3d(0, -50%, 0); border-top: 20px solid transparent; border-bottom: 20px solid transparent; border-right: 20px solid #FFE47F; }
      }
    }

    // 超值特购
    &.is-subsidy{
      position: relative;
      padding: 0 20px 20px;
      .banner-bg {
        position: absolute;
        inset: 0;
        height: 104px;
      }
      .subsidy-price-bar {
        position: relative;
        display: flex;
        width: 100%;
        color: #FFFFFF;
        height: 104px;

        .left{
          flex: 1;
          display: flex;
          justify-content: space-between;
          .final-price{
            padding-top: 10px;
            display: flex;
            align-items: baseline;
            .prefix{
              font-size: 30px;
            }
            .amount{
              font-size: 56px;
              display: flex; align-items: baseline;
              &:after{ content: attr(data-value);
                font-size: 30px; padding-bottom: 3px; font-weight: normal;}
            }
          }

          .discount{
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding-right: 40px;
            .amount{
              flex: none;
              border-radius: 20px;
              padding: 1px 16px;
              background: #FFFFFF;
              color: #E92828;
              font-size: 24px;
              text-align: center;
              margin-bottom: 10px;
            }
            .original{
              font-size: 24px;
            }
          }
        }

        .right{
          text-align: right;
          color: #9B542E;
          font-size: 26px;
          width: 160px;
          display: flex;
          flex-direction: column;
          justify-content: center;
        }
      }

      ._sales{ color: #646464; font-size: 24px; padding: 20px 0; text-align: right;}

      .countdown{
        display: flex;
        justify-content: flex-end;
        color: #9B542E;
        font-size: 26px;
        margin-top: 10px;
        .li{
          width: 35px;
          height: 35px;
          background: #9B542E;
          color: #FFFFFF;
          border-radius: 8px;
          text-align: center;
          &:nth-child(5){
            position: relative;
            .millisecond{
              width: 100%;
              position: absolute;
              top: 50%;
              transform: translateY(-50%);
              filter: brightness(100);
            }
          }
        }
        .delimiter{
          margin: 0 8px;
        }
      }
    }

    &.is-template-3{
      .template3-price-bar {
        position: relative;
        display: flex;
        width: 100%;
        color: #FFFFFF;
        height: 126px;

        .left{
          padding: 0 24px;
          flex: 1;
          background: linear-gradient(90deg, #FF517B 0%, #FF3F39 100%);
          display: flex;
          flex-direction: column;
          justify-content: center;
          .final-price{
            display: flex;
            align-items: flex-end;
            font-size: 24px;
            .prefix{
              font-size: 26px;
            }
            .amount{
              font-size: 50px;
              display: flex;
              line-height: 1em;
              align-items: baseline;
            }

            .discount{
              margin-top: 6px;
              margin-left: 10px;
              color: #EB431F;
              background: #FFD3AB;
              border-radius: 50px;
              padding: 4px 14px;
            }
          }

          .original{
            font-size: 24px;
            color: #FFDDC4;
          }
        }

        .right{
          padding: 0 30px;
          color: #9B542E;
          font-size: 26px;
          background: #FFC549;
          width: 206px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .countdown-title{
            font-weight: 500;
          }
        }
      }
      .countdown{
        display: flex;
        justify-content: flex-end;
        color: #7C2A04;
        font-size: 26px;
        margin-top: 10px;
        .li{
          width: 38px;
          height: 38px;
          line-height: 38px;
          background: #F3800D;
          color: #FFFFFF;
          border-radius: 10px;
          text-align: center;
          font-size: 22px;
        }
        .delimiter{
          color: #FFFFFF;
          margin: 0 8px;
        }
      }
    }

    // 无内容
    &.is-empty{ padding: 20px 0 20px 0;}
  }
</style>
